package com.sino.androiddesign.recyclerviewdemo


import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.Toast


import com.sino.androiddesign.R
import kotlinx.android.synthetic.main.fragment_multiple_item.*
import kotlin.NullPointerException

/**
 * 多条目布局
 *
 */
class MultipleItemFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_multiple_item, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val linearLayoutManager = LinearLayoutManager(context, LinearLayout.VERTICAL, false)
        multiple_Rv.layoutManager = linearLayoutManager
        val datas: ArrayList<String> = ArrayList()
        for (i in 0 until 20) {
            datas.add("test $i")
        }
        multiple_Rv.adapter = MultipleAdapter(datas, context!!)
        val customDividerLine = CustomDividerLine(context!!, CustomDividerLine.LINE_HORIZONTAL)
        multiple_Rv.addItemDecoration(customDividerLine)


        horizontal_btn.setOnClickListener {
            if (linearLayoutManager.orientation == LinearLayout.HORIZONTAL){
                Toast.makeText(context,"已经是横向排列了",Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            //todo 可以通过layoutManager 的设置方向改变排序
            linearLayoutManager.orientation = LinearLayout.HORIZONTAL
            customDividerLine.setOrientation(CustomDividerLine.LINE_VERTICAL)
            multiple_Rv.adapter.notifyDataSetChanged()

        }
        vertical_btn.setOnClickListener {
            if (linearLayoutManager.orientation == LinearLayout.VERTICAL){
                Toast.makeText(context,"已经是纵向排列了",Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            linearLayoutManager.orientation = LinearLayout.VERTICAL
            customDividerLine.setOrientation(CustomDividerLine.LINE_HORIZONTAL)
            multiple_Rv.adapter.notifyDataSetChanged()
        }
    }


}

class MultipleAdapter(private var datas: ArrayList<String>, private var mContext: Context) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    private val TAG_ONE: Int = 1
    private val TAG_TWO: Int = 2

    override fun getItemViewType(position: Int): Int {
        return if (position % 3 == 0) {
            TAG_TWO
        } else {
            TAG_ONE
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        var layoutInflater = LayoutInflater.from(mContext)
        return if (viewType == TAG_ONE) {
            var rootView: View = layoutInflater.inflate(R.layout.fragment_multiple_item_one, parent, false)
            OneItemHolder(rootView)
        } else {
            var rootView: View = layoutInflater.inflate(R.layout.fragment_multiple_item_two, parent, false)
            TwoItemHolder(rootView)
        }
    }

    override fun getItemCount(): Int {
        return datas.size
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is OneItemHolder) {

        } else {

        }
    }
}

class OneItemHolder(itemView: View?) : RecyclerView.ViewHolder(itemView)

class TwoItemHolder(itemView: View?) : RecyclerView.ViewHolder(itemView)

/**
 * 自定义 线条
 *
 * 先提供一个默认的 线条,, 再提供一个 可以更改的线条
 * todo  理解线条的问题:
 * todo 1P::对于每个子view,都会先执行getItemOffsets 这个方法 ,其中outRect 这个参数相当于对原view 添加一个填充距离
 * todo 就像在 原子view的 给定的方向 添加一定长度的空间
 * todo 2P:: 执行完 getItemOffsets,之后才会绘制 线条, 以横线为例:
 * todo 首先会判断recyclerView 左右是否 有内边距 ,用来确定线的左起点,clipRect()这个方法就相当于截取这个view的展示,不会消失,只是固定展示
 * todo  parent.getDecoratedBoundsWithMargins(child,mBounds) 是把这个view的外边框(也就是添加的outReact之后的view的具体视图)位置信息
 * todo  赋值给 mBounds(Rect,这个高度是一直累加的状态) 左右位置根据rv来得到,线条的绘制y轴位置: bottom 就是mBounds的bottom(有过子view有偏移量需要添加translationY)
 * todo 绘制的top位置 就是 bottom - 线条高度 ; 线条就是一个drawable(shape),做好之后直接引用
 */
class CustomDividerLine : RecyclerView.ItemDecoration {


    private lateinit var mContext: Context

    private lateinit var mDrawable: Drawable
    private var orientation: Int = LINE_HORIZONTAL
    private val mBounds: Rect = Rect()

    companion object {
        const val LINE_HORIZONTAL = 0 //横线
        const val LINE_VERTICAL = 1    //竖线
    }

    constructor(context: Context, orientation: Int) {
        mContext = context
        setOrientation(orientation)

        mDrawable = if (orientation == LINE_VERTICAL) {
            mContext.getDrawable(R.drawable.shape_w1)
        } else {
            mContext.getDrawable(R.drawable.shape_h1)
        }

    }


    fun setOrientation(orientation: Int) {
        if ((orientation != LINE_HORIZONTAL) and (orientation != LINE_VERTICAL)) {
            throw NullPointerException("方向有错误")
        }
        this.orientation = orientation

        mDrawable = if (orientation == LINE_VERTICAL) {
            mContext.getDrawable(R.drawable.shape_w1)
        } else {
            mContext.getDrawable(R.drawable.shape_h1)
        }
    }

    override fun onDraw(c: Canvas?, parent: RecyclerView?, state: RecyclerView.State?) {
        super.onDraw(c, parent, state)
        println("multipleItem  onDraw")
        if (mDrawable == null) {
            return
        }
        c!!.save()
        when (orientation) {

            LINE_VERTICAL -> {  // 竖线
                println("multipleItem  LINE_VERTICAL")
                val top: Int
                val bottom: Int
                if (parent!!.clipToPadding) {
                    top = parent.paddingTop
                    bottom = parent.height - parent.paddingBottom
                    c.clipRect(parent.paddingLeft, top, parent.width - parent.paddingBottom, bottom)
                } else {
                    top = 0
                    bottom = parent.height
                }
                for (i in 0 until parent.childCount) {
                    val child = parent.getChildAt(i)
                    parent.getDecoratedBoundsWithMargins(child, mBounds)
                    val right: Int = mBounds.left + Math.round(child.translationX)
                    val left: Int = right - mDrawable.intrinsicWidth
                    mDrawable.setBounds(left, top, right, bottom)
                    mDrawable.draw(c)
                }
                println("multipleItem  LINE_VERTICAL")
            }

            LINE_HORIZONTAL -> {
                val left: Int
                val right: Int
                if (parent!!.clipToPadding) {
                    left = parent.paddingLeft
                    right = parent.width - parent.paddingRight
                    c.clipRect(left, parent.paddingTop, right, parent.height - parent.paddingBottom)
                } else {
                    left = 0
                    right = parent.width
                }

                for (i in 0 until parent.childCount) {
                    val child = parent.getChildAt(i)
                    if (i == 0) {
                        println("multipleItem ${child.height}+${child.top}+${child.bottom}")
                    }
                    println("multipleItem  第一次: $mBounds")
                    parent.getDecoratedBoundsWithMargins(child, mBounds)
                    println("multipleItem  第二次 mBounds: $mBounds")
                    var bottom: Int = mBounds.bottom + Math.round(child.translationY)
                    println("multipleItem  第二次 view偏移量:  ${Math.round(child.translationY)}")
                    var top: Int = bottom - mDrawable.intrinsicHeight
                    mDrawable.setBounds(left, top, right, bottom)
                    mDrawable.draw(c)
                }
            }
        }
        c!!.restore()
    }

    override fun getItemOffsets(outRect: Rect?, view: View?, parent: RecyclerView?, state: RecyclerView.State?) {
        println("multipleItem  getItemOffsets  给每个孩子进行填充的 outRect")

        if (orientation == LINE_HORIZONTAL) {
            outRect!!.set(0, 10, 0, mDrawable.intrinsicHeight + 10)

            println("multipleItem  $outRect")

        } else {
            outRect!!.set(10, 0, mDrawable.intrinsicWidth + 10, 0)
        }

    }

}

